import React from 'react';
import {inject, observer} from 'mobx-react';
import ExportList from "./ExportList";
import ExportList2 from "./ExportList2";
import {toJS} from 'mobx';

import {
  WeaTop,
  WeaRightMenu,
  WeaFormItem,
  WeaTools,
  WeaLocaleProvider,
  WeaRadioGroup,
  WeaAlertPage,
  WeaTransfer,
  WeaDialog,
  WeaInputSearch 
} from 'ecCom';

const getKey = WeaTools.getKey;
import {Button} from 'antd';
import {WeaSwitch} from 'comsMobx';

const getLabel = WeaLocaleProvider.getLabel;

import BlogConstant from '../../util/BlogConstant';
import BlogExportIndex from '../blogExport/BlogExportIndex';


@inject('blogContentExportStore')
@observer
export default class ContentExport extends React.Component {
  constructor(props) {
    super(props);
  }

  componentDidMount() {
    const {blogContentExportStore} = this.props;
    blogContentExportStore.doInit();
  }

  componentWillReceiveProps(nextProps) {
    const {blogContentExportStore} = this.props;
    if (this.props.location.key !== nextProps.location.key) {
      blogContentExportStore.doInit();
    }
  }

  getBtns = (ecId) => {
    const {blogContentExportStore} = this.props;
    const {alertPage,operateBlogBackstageExport,setExportPermissionsListIsShow} = blogContentExportStore;
    let btns = [
      <Button ecId={`${ecId}_Button@kq6uob@$exeportexcel`}
        type='primary'
        onClick={() => {
          operateBlogBackstageExport(blogContentExportStore.radioGroupParams);
        }}>
        {getLabel(28343, '导出Excel')}
      </Button>,
      !alertPage?
       <Button ecId={`${ecId}_Button@l3o32d@powersetting`}
        type='primary'
        onClick={() => {
          setExportPermissionsListIsShow(true);
        }}>
        {getLabel(501864, '权限设置')}
      </Button>:'',
    ]
    return btns;
  }

  getRightMenu() {
    const {blogContentExportStore} = this.props;
    let btnArr = [
      {
        key: 'BTN_EXPORT',
        icon: <i className='icon-coms-export'/>,
        content: `${getLabel(28343, '导出Excel')}`,
        onClick: () => {  blogContentExportStore.operateBlogBackstageExport(blogContentExportStore.radioGroupParams);}
      },
      {
        key: '10',
        icon: <i className="icon-coms-Custom" />,
        content: getLabel('32535', '显示列定制'),
        onClick: () => {blogContentExportStore.submitStatus=='3'?blogContentExportStore.showColumn2():blogContentExportStore.showColumn()}
       },
       {
        key: '11',
        icon: <i className="icon-coms-Custom" />,
        content: getLabel(389339, '默认排序设置'),
        onClick: () => {blogContentExportStore.setExportListSortIsShow(true)}
       }
    ]
    return btnArr;
  }

  // renderItem(item){
  //   if(item.state=='1'){
  //     return <div class="tree-title">{item.name}          {item.orderBy=='asc'?getLabel('21605','正序'):getLabel('21604','倒序') }</div>
  //   }else{
  //     return <div class="tree-title">{item.name}</div>
  //   }
    /**
     * 数据渲染
     * @param item
     * @returns {*}
     */
    renderItem = (item) => {
      const {blogContentExportStore} = this.props;
      const {selectedKeys} = blogContentExportStore;
      let sldk = toJS(selectedKeys);
      let orderTypeComp = <div></div>;
      if (sldk.indexOf(item.id) != -1) {//是否是右侧选中值
          orderTypeComp = (
              <span style={{float: 'right', cursor: 'pointer', marginRight: "15px"}} onClick={e => this.fnClickOrderType(e, item)} onDoubleClick={e =>this.fnStopPropagation(e)}>
                  {item.orderBy != 'asc' ? getLabel(21604,'倒序') : getLabel(21605,'正序')}
              </span>
          );//从新设置相关信息
      }
      return (
          <div style={{height: '37px', lineHeight: '37px', padding: '0 15px', borderBottom: '1px solid #e2e2e2'}} title={item.name}>
              <span>{item.name}</span>
              {orderTypeComp}
          </div>
      );//定制化设置
  }

  //取消冒泡
  fnStopPropagation = (e) => {
    e.preventDefault && e.preventDefault();
    e.stopPropagation && e.stopPropagation();
}

/**
 * 右侧排序点击事件
 * @param e
 * @param item
 */
fnClickOrderType = (event, item) => {
    try{
        this.fnStopPropagation(event);
    } catch (e) { }
    const {blogContentExportStore} = this.props;
    const {sortData, updateInitData} = blogContentExportStore;
    let ds = toJS(sortData);
    for (let i = 0  ; i < ds.length; i++) {//修改排序顺序
        if (ds[i].id == item.id) {
            ds[i].orderBy = ds[i].orderBy != 'asc' ? 'asc' : 'desc';
        }
    }
    
    updateInitData(ds);
}


  updateSort(keys,datas){
    const {setSelectedKeys} = this.props.blogContentExportStore;
    setSelectedKeys(keys);
  }

  updateValue= (str, wy) => {
    const {blogContentExportStore} = this.props;
    const {updateRightValue, updateLeftValue} = blogContentExportStore;
    if (wy == "right") {
        updateRightValue(str);
    } else {
        updateLeftValue(str);
    }
}

     /**
     * 快捷搜索右侧数据过滤
     * @param items
     * @returns {*}
     */
    filterRight = (items) =>{
      const {blogContentExportStore} = this.props;
      const {rightvalue} = blogContentExportStore;
      if (rightvalue) {
          items = items.filter(item=> item.name.indexOf(rightvalue) >= 0);//filter过滤数据
      }
      return items;
  }

  fnclearnsearch=()=> {
    const {blogContentExportStore} = this.props;
    const {updateRightValue,updateLeftValue,} = blogContentExportStore;
    updateLeftValue("");
    updateRightValue("");
}

    /**
     * 左侧数据快捷搜索数据过滤
     * @param items
     * @returns {*}
     */
    filterLeft = (items) => {
      const {blogContentExportStore} = this.props;
      const {leftvalue} = blogContentExportStore;
      if (leftvalue) {
          items = items.filter(item=> item.name.indexOf(leftvalue) >= 0);//filter过滤数据
      }
      return items
  }

  fnSaveData(v) {
    const {blogContentExportStore} = this.props;
    const {sortData, selectedKeys,updateExportSort} = blogContentExportStore;
    let rightData="";
    let leftData = "";
    let sort = 1;
    let sKeys = toJS(selectedKeys);
    let sData = toJS(sortData);
    sKeys.map(index=>{
      sData.map(item=>{
            if(item.id == index) {
              rightData+=item.colName+","+ item.orderBy+",1"+";";
              sort++;
            }
        }) ;
    })
    let isIn = false;
    sData.map(item=>{
      sKeys.map(index=>{
            if(item.id == index) {
              isIn = true;
            }
        }) ;
        if(!isIn){
          leftData += item.colName+","+ item.orderBy+";";
        }
    })
    updateExportSort({rightData:rightData,leftData:leftData,sKeys:sKeys.toString()});
    //发送保存请求，修改数据，
    // WeaTools.callApi('/api/workflow/reqlist/doSaveData', 'POST', {datajson: JSON.stringify(datas), dataKey}).then(data=>{
    //     onCancel(false);
    //     if(data.stauts) {
    //         message.success(getLabel(22619,"保存成功"))
    //         wfListDoingStore.doSearch();
    //     } else {
    //         message.error(getLabel(22620, "保存失败")+","+getLabel(126690,"请联系管理员!"))
    //     }
    // });
}




  render() {
    const {blogContentExportStore} = this.props;
    const {conditionInfo, loading} = toJS(blogContentExportStore.status);
    const collectParams = {
      favname: `${getLabel(385290, '内容导出')}`,
      favouritetype: 1,
      objid: 0,
      link: 'wui/engine.html#/blogengine/export',
      importantlevel: 1,
    };
    const {alertPage,submitStatus,leftvalue,rightvalue} = this.props.blogContentExportStore;
    let buttons = [
      (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@m5ocb1@save`} type="primary" onClick={(v) => {this.fnSaveData(v);this.fnclearnsearch()}}>{getLabel(86, "保存")}</Button>),
      (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@akf9o3@cancel`} type="ghost" onClick={() => {blogContentExportStore.setExportListSortIsShow(false);this.fnclearnsearch()}}>{getLabel(201, "取消")}</Button>)
    ]
    return (
      <div className="wea-bs-blog-applyset" style={{height: '100%'}}>
      {
     
        <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@514yoh`}
          datas={this.getRightMenu()}
          collectParams={collectParams}
        >
          <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@0v31vh`}
            title={getLabel(385290, '内容导出')}
            icon={BlogConstant.icon}
            iconBgcolor={BlogConstant.iconBgColor}
            loading={loading}
            buttonSpace={10}
            buttons={this.getBtns(this.props.ecId || '')}
            showDropIcon={true}
            dropMenuDatas={
              this.getRightMenu()
            }
            dropMenuProps={{
              collectParams: collectParams
            }}
          />
          <WeaRadioGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaRadioGroup@zq3by2`} config={conditionInfo}  beforeInit={(a,b,c)=>{c(b);}}  onChange={(params)=> {blogContentExportStore.updateRadioGroupParams(params);}}/>
          {submitStatus=='3'? <ExportList2 ecId={`${this && this.props && this.props.ecId || ''}_ExportList2@ayml67`}/>: <ExportList ecId={`${this && this.props && this.props.ecId || ''}_ExportList@guhcra`}/>}
             <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@qc3rk5`}
                    onCancel={() =>{
                      blogContentExportStore.setExportListSortIsShow(false);
                      this.fnclearnsearch()
                    }}
                    buttons={buttons}
                    maskClosable={false}
                    title={getLabel(389339, '默认排序设置')}
                    visible={blogContentExportStore.exportSortListIsShow}
                    style={{ width: 1000, height: 500 }}
                    hasScroll
                    >
                <WeaTransfer ecId={`${this && this.props && this.props.ecId || ''}_WeaTransfer@gumslc`} 
                  ref="myWeaTransferId"
                  className="portal-element-showfieldnew"
					      	data={toJS(blogContentExportStore.sortData)}
                  selectedKeys={toJS(blogContentExportStore.selectedKeys)}
                  renderItem={this.renderItem}
                  filterLeft={this.filterLeft}
                  filterRight={(items) =>this.filterRight(items)}
                  onChange={(keys, datas)=>this.updateSort(keys,datas)}
                  rightHeader={
                    <div style={{ position: 'relative'}}>
                        <span style={{paddingLeft: '15px'}}>{getLabel(83303, '已选')}</span>
                        <div style={{float:"right",width:"100px", marginRight: "10px"}}>
                            <WeaInputSearch ecId={`${this && this.props && this.props.ecId || ''}_WeaInputSearch@sxqaxw`} onSearchChange={lvalue => this.updateValue(lvalue, "right")} onSearch={lvalue => this.updateValue(lvalue, "right")}/></div></div>
                  }
                
                        //原始样式来源，可以基于本样式修改
                      /*  leftHeader= <div style={{display: 'inline-block', position: 'relative'}}><span style={{paddingLeft: '15px', position: 'absolute',
                        width: '100px', textAlign: 'left', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', display: 'block', top: '-25px'}}>{getLabel(83303, '已选')}</span><div style={{position: 'absolute',
                        top: '-25px',  width: '90px', left: '238px'}}><WeaInputSearch onSearch={(value)=>this.setState({rightSearchName: value})}/></div></div> */
                        leftHeader={<div style={{ position: 'relative'}}>
                            <span style={{paddingLeft: '15px'}}>{getLabel(83302, '待选')}</span>
                            <div style={{float:"right",width:"100px", marginRight: "10px"}}>
                                <WeaInputSearch ecId={`${this && this.props && this.props.ecId || ''}_WeaInputSearch@w3xtjv`} onSearchChange={lvalue => this.updateValue(lvalue, "left")} onSearch={lvalue =>  this.updateValue(lvalue, "left")}/></div></div>}
                    />

                </WeaDialog>
                <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@17flul`}
                    onCancel={() =>
                        blogContentExportStore.setExportPermissionsListIsShow(false)
                    }
                    title={getLabel(501864, '权限设置')}
                    visible={blogContentExportStore.exportPermissionsListIsShow}
                    style={{ width: 1000, height: 580 }}
                    >
            
                 <BlogExportIndex ecId={`${this && this.props && this.props.ecId || ''}_BlogExportIndex@89mkmc`}/>
                </WeaDialog>

        </WeaRightMenu>
      }
      </div>
    )
  }
}